<template>
  <div>
    <div class="deepBackground">
      <!--树形控件（部门显示）-->
      <div style="display: flex;align-items: center;justify-content: center;width: 20%;margin: 6px;border-radius: 12px;background-color: white;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);height: 100%;flex-direction: column;
">
        <el-tree
            :data="treeData"
            :props="defaultProps"
            accordion
            @node-click="handleNodeClick">
        </el-tree>

      </div>
      <!--      表格和查询条件区域-->
      <div style="display: flex;flex-direction: column;width: 80%;border-radius: 12px;background-color: white;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);height: 100%;align-items: center;
" id="tableArea">
        <!--                      条件搜索区域
                <div style="display: flex;align-items: center;justify-content: center;width: 100%; height: 8vh">
                  <div style="width: 30%; display: flex;align-items: center;justify-content: center">
                    <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">日志名称:</span>
                    &lt;!&ndash;            <el-select v-model="projectSelectValue" placeholder="请选择所属项目">&ndash;&gt;
                    <el-input v-model="noteNameSelectValue" placeholder="请输入日志名称" size="small" style="width: auto"></el-input>
                  </div>

                  <div style="width: 30%; display: flex;align-items: center;justify-content: center">
                    <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">日志类型:</span>
                    <el-select v-model="noteTypeSelectValue" placeholder="请选择日志类型">
                      <el-option
                          v-for="item in noteTypeOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                      </el-option>
                    </el-select>
                  </div>

                  <div style="width: 30%; display: flex;align-items: center;justify-content: center">
                    <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">发布日期:</span>
                    <el-date-picker
                        v-model="publishTimeSelectValue"
                        type="date"
                        placeholder="选择日期">
                    </el-date-picker>

                  </div>

                  <div style="width: 30%; display: flex;align-items: center;justify-content: center">
                    <el-button type="primary" style="width: 37%;margin: 12px" @click="getMyNotesConditional">搜索
                    </el-button>
                    <el-button style="width: 37%;margin: 12px" @click="reSetMyNoteSelectCondition">重置
                    </el-button>
                  </div>
                </div>-->
        <!--      表格头-->
        <div
            style="display: flex;align-items: center;justify-content: center;height: 5%;margin: 6px;width: 100%">

          <div style="display: flex;align-items: center;justify-content: left;width: 30%">
            <Span style="font-size: 24px;font-family: 'PingFang SC';font-weight: bolder;margin-left: 12px">员工管理</Span>

          </div>

          <div style="display: flex;align-items: center;justify-content: right;width: 70%;margin: 12px">
            <!--            &lt;!&ndash;              任务状态选择&ndash;&gt;
                        <el-radio-group v-model="tabPosition">
                          <el-radio-button label="all" @click.native="changeTab('all')">全部</el-radio-button>
                          <el-radio-button label="save" @click.native="changeTab('save')">保存未发布</el-radio-button>
                          <el-radio-button label="timed" @click.native="changeTab('timed')">定时发布</el-radio-button>
                          <el-radio-button label="published" @click.native="changeTab('published')">已发布</el-radio-button>
                        </el-radio-group>-->
            <!--              任务模糊查询-->
            <!--            新增员工-->
            <el-button type="success" plain style="margin: 12px" @click="addUserDialogShow">新增员工</el-button>
            <!--              任务状态选择-->
            <el-radio-group v-model="tabPosition">
              <el-radio-button label="all" @click.native="changeTab('all')">全部</el-radio-button>
              <el-radio-button label="normal" @click.native="changeTab('normal')">普通员工</el-radio-button>
              <el-radio-button label="leader" @click.native="changeTab('leader')">项目组长</el-radio-button>
              <el-radio-button label="manager" @click.native="changeTab('manager')">部门领导</el-radio-button>
            </el-radio-group>
            <el-input
                placeholder="请输入员工Id进行搜索"
                v-model="searchValue" style="width: 30%;margin-left: 10px;margin-right: 12px;">
            </el-input>
            <el-button type="primary" icon="el-icon-search" @click="selectUser()">搜索</el-button>

          </div>
        </div>
        <!--      表格本体-->
        <div style="display: flex;justify-items: center;margin: 12px;height: 85vh;width: 100%">
          <el-table
              :data="tableData"
              height="80vh"
              style="width: 100%;margin: 12px;"
              stripe="true"
          >

            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="员工Id">
                    <span>: {{ props.row.uid }}</span>
                  </el-form-item>
                  <el-form-item label="账号">
                    <span>: {{ props.row.name }}</span>
                  </el-form-item>
                  <el-form-item label="姓名">
                    <span>: {{ props.row.infoName }}</span>
                  </el-form-item>
                  <el-form-item label="电话">
                    <span>: {{ props.row.phone }}</span>
                  </el-form-item>
                  <el-form-item label="邮箱">
                    <span>: {{ props.row.email }}</span>
                  </el-form-item>
                  <el-form-item label="性别">
                    <span>: {{ props.row.gender }}</span>
                  </el-form-item>
                  <el-form-item label="个人简介">
                    <span>: {{ props.row.introduction }}</span>
                  </el-form-item>
                  <el-form-item label="职位">
                    <span>: {{ props.row.jobType }}</span>
                  </el-form-item>
                  <el-form-item label="部门">
                    <span>: {{ props.row.depName }}</span>
                  </el-form-item>
                  <el-form-item label="权限角色">
                    <span>: {{ props.row.roleName }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>


            <el-table-column
                prop="uid"
                label="员工Id"
            >
            </el-table-column>
            <el-table-column
                prop="infoName"
                label="员工姓名"
            >
            </el-table-column>
            <el-table-column
                prop="depName"
                label="所属部门">

              <template slot-scope="scope">
                <el-tag
                    disable-transitions
                    effect="Plain"
                >{{ scope.row.depName }}
                </el-tag>
              </template>

            </el-table-column>

            <el-table-column
                prop="jobType"
                label="职位">
              <template slot-scope="scope">
                {{ scope.row.jobType }}
              </template>
            </el-table-column>

            <el-table-column
                prop="roleName"
                label="权限角色"
            >
              <template slot-scope="scope">
                <el-tag
                    disable-transitions
                    effect="dark"
                >{{ scope.row.roleName }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="操作"
                             width="270px"
            >
              <template slot-scope="scope">

                <el-button
                    size="mini"
                    @click="editUserDialogShow(scope.row.uid)"
                    plain
                >编辑
                </el-button>
                <el-button
                    size="mini"
                    type="danger"
                    @click="delUserAllData(scope.row.uid)"
                    plain
                >删除
                </el-button>
                <el-button
                    size="mini"
                    type="success"
                    @click="roleAllocationDialogShow(scope.row.uid)"
                    plain
                >权限分配
                </el-button>
              </template>
            </el-table-column>
          </el-table>


          <!--          权限分配弹窗-->
          <el-dialog
              title="权限分配"
              :visible.sync="roleVisible"
              width="50%"
          >
            <div style="display: flex;align-items: center;justify-content: center">

              <el-select v-model="roleValue" placeholder="请选择要赋予的权限">
                <el-option
                    v-for="item in roleOptionValue"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>

            </div>



            <span slot="footer" class="dialog-footer">
    <el-button @click="unshowRoleVisible">取 消</el-button>
    <el-button type="primary" @click="updateUserRole">确 认</el-button>
  </span>
          </el-dialog>



          <!--          编辑用户信息弹窗-->
          <el-dialog
              title=员工信息
              :visible.sync="editUserDialogVisible"
              width="50%"
          >
            <div style="display: flex;align-items: center;flex-direction: column ;width: 100%">


              <el-form label-position="top"
                       style="display: flex; justify-content: center;flex-direction: column;width: 100%"
                       :model="editUserEntity" :rules="infoRules">
                <!--                无法更改的内容：账号、职位、部门、-->
                <div style="display: flex ;justify-content: center;align-items: center">
                  <el-form-item label="账号" style="width: 100%;margin: 6px">
                    <el-input disabled='true' v-model="editUserEntity.name"></el-input>
                  </el-form-item>
                  <el-form-item label="职位" style="width: 100%;margin: 6px">
                    <el-input disabled='true' v-model="editUserEntity.roleName"></el-input>
                  </el-form-item>
                </div>

                <div style="display: flex ;justify-content: left;align-items: center">
                  <el-form-item label="部门" style="width: 48%;margin: 6px">
                    <el-select v-model="editUserEntity.depName" placeholder="请选择部门">
                      <el-option
                          v-for="item in departmentOptions"
                          :key="item.label"
                          :label="item.label"
                          :value="item.label">
                      </el-option>
                    </el-select>
                    <!--                    <el-input v-model="editUserEntity.depName"></el-input>-->
                  </el-form-item>
                </div>
                <!--                可以更改的内容：姓名、邮箱、电话、性别、个人介绍-->
                <div style="display: flex ;justify-content: center;align-items: center">
                  <el-form-item label="姓名" style="width: 100%;margin: 6px">
                    <el-input v-model="editUserEntity.infoName"></el-input>
                  </el-form-item>
                  <el-form-item label="邮箱" style="width: 100%;margin: 6px">
                    <el-input v-model="editUserEntity.email"></el-input>
                  </el-form-item>
                </div>

                <div style="display: flex ;justify-content: center;align-items: center">
                  <el-form-item label="电话" style="width: 100%;margin: 6px">
                    <el-input v-model="editUserEntity.phone"></el-input>
                  </el-form-item>
                  <el-form-item label="性别" style="width: 100%;margin: 6px">
                    <el-select placeholder="" style="width: 100%" v-model="editUserEntity.gender">
                      <el-option label="男" value="男"></el-option>
                      <el-option label="女" value="女"></el-option>
                    </el-select>
                  </el-form-item>
                </div>

                <div style="display: flex ;justify-content: center;align-items: center">
                  <el-form-item label="个人信息" style="width: 100%;margin: 6px">
                    <el-input type="textarea" :autosize="{ maxRows: 6}"
                              v-model="editUserEntity.introduction" maxlength="30" show-word-limit></el-input>
                  </el-form-item>
                </div>


              </el-form>
            </div>


            <span slot="footer" class="dialog-footer">
    <el-button @click="editUserDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo">修 改</el-button>
  </span>
          </el-dialog>

          <!--新增员工弹窗-->
          <el-dialog
              title="新增员工"
              :visible.sync="addUserDialogVisible"
              width="50%"
          >
            <div style="display: flex;align-items: center;flex-direction: column ;width: 100%">


              <el-form label-position="top"
                       style="display: flex; justify-content: center;flex-direction: column;width: 100%"
                       :model="addUserEntity" :rules="infoRules">
                <!--                无法更改的内容：账号、职位、部门、-->
                <div style="display: flex ;justify-content: center;align-items: center">
                  <el-form-item label="账号" style="width: 100%;margin: 6px">
                    <el-input  v-model="addUserEntity.name"></el-input>
                  </el-form-item>
                  <el-form-item label="职位" style="width: 100%;margin: 6px">
                    <el-input  disabled="true" v-model="addUserEntity.roleName"></el-input>
                  </el-form-item>
                </div>

                <div style="display: flex ;justify-content: left;align-items: center">
                  <el-form-item label="部门" style="width: 48%;margin: 6px">
                    <el-select v-model="addUserEntity.depName" placeholder="请选择部门">
                      <el-option
                          v-for="item in departmentOptions"
                          :key="item.label"
                          :label="item.label"
                          :value="item.label">
                      </el-option>
                    </el-select>
                    <!--                    <el-input v-model="editUserEntity.depName"></el-input>-->
                  </el-form-item>
                </div>
                <!--                可以更改的内容：姓名、邮箱、电话、性别、个人介绍-->
                <div style="display: flex ;justify-content: center;align-items: center">
                  <el-form-item label="姓名" style="width: 100%;margin: 6px">
                    <el-input v-model="addUserEntity.infoName"></el-input>
                  </el-form-item>
                  <el-form-item label="邮箱" style="width: 100%;margin: 6px">
                    <el-input v-model="addUserEntity.email"></el-input>
                  </el-form-item>
                </div>

                <div style="display: flex ;justify-content: center;align-items: center">
                  <el-form-item label="电话" style="width: 100%;margin: 6px">
                    <el-input v-model="addUserEntity.phone"></el-input>
                  </el-form-item>
                  <el-form-item label="性别" style="width: 100%;margin: 6px">
                    <el-select placeholder="" style="width: 100%" v-model="addUserEntity.gender">
                      <el-option label="男" value="男"></el-option>
                      <el-option label="女" value="女"></el-option>
                    </el-select>
                  </el-form-item>
                </div>



              </el-form>
            </div>

            <span slot="footer" class="dialog-footer">
    <el-button @click="addUserDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">新 增</el-button>
  </span>
          </el-dialog>



        </div>
        <!--     分页组件 -->
        <div style="display: flex;align-items: center;justify-content: center;margin: 6px">
          <el-pagination
              class="pagination"
              background
              layout="prev, pager, next"
              :pageSize="pageSize"
              :total="total"
              @current-change="change"
          >
          </el-pagination>
        </div>


      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "EmployeeManagement",
  data() {

    var validPhone = (rule, value, callback) => {
      //校验中国电话号码的正则表达式
      const chinesePhoneNumberRegex = /^1[3456789]\d{9}$/;
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!chinesePhoneNumberRegex.test(value)) {
        callback(new Error('请输入正确的手机号！'))
      } else {
        callback();
      }
    }

    var validEmail = (rule, value, callback) => {
      //校验中国电话号码的正则表达式
      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (value === '') {
        callback(new Error('请输入邮箱'))
      } else if (!emailRegex.test(value)) {
        callback(new Error('请输入正确的邮箱！'))
      } else {
        callback();
      }
    }
    return {

      loginUser: JSON.parse(localStorage.getItem("loginUser")), //当前登录用户
      userRole: localStorage.getItem("loginUserRole"),
      treeData: [], //树形控件展示数据（部门信息）
      tableData: [], //表格绑定数据

      //分页相关的数据绑定
      pageSize: 15, //设置默认值为12条一页
      total: 0,
      pageNum: 1,

      switchValue: false,//switch组件数据绑定
      tabPosition: 'all',//员工权限选择框数据绑定

      userRoleSelectValue: 4, //默认查询所有权限的用户
      editUserDialogVisible: false,//编辑用户信息弹窗显示绑定
      editUserEntity: {}, //编辑用户信息绑定实体

      //表单校验规则
      infoRules: {
        infoName: [
          {required: true, message: '请输入用户名！', trigger: 'blur'}
        ],
        phone: [
          {validator: validPhone, trigger: 'blur'}
        ],
        email: [
          {validator: validEmail, trigger: 'blur'}
        ]
      },

      departmentOptions: [], //部门选项
      addUserDialogVisible: false,//新增员工弹窗显示绑定

      roleVisible: false, //权限分配弹窗显示绑定

      //新增用户实体绑定
      addUserEntity:{
        name:'',
        roleName:'普通员工',
        depName:'',
        infoName:'',
        email:'',
        phone:'',
        gender:'',
        introduction:'',
      },
      searchValue:"", //条件查询数据绑定

      roleValue:"",//权限分配选择权限
      roleOptionValue:[
        {
          value: 3,
          label: '普通员工'
        },{
          value: 2,
          label: '项目组长'
        },{
          value: 1,
          label: '部门领导'
        },
      ],
      updateUserRoleId:"",//被选中的要修改权限的userId

    }
  },
  mounted() {
    //页面加载时查询到相应的部门信息
    this.$request.get("/department/getDepartment", {
      params: {
        userRole: this.userRole
      }
    }).then(res => {
      if (res.successFlag) {
        this.treeData = res.data
      } else {
        this.$message.error(res.errorMsg)
      }
    })
    //加载table数据
    this.$request.get("/user/getUserForManagerConditional", {
      params: {
        depName: "",
        userRole: this.userRoleSelectValue,
        currentPage: this.pageNum,
        pageSize: this.pageSize
      }
    }).then(res => {
      if (res.successFlag) {
        this.tableData = res.data.pageData
        this.total = res.data.totalData
      } else {
        this.$message.error(res.errorMsg)
      }
    })

    //加载可选部门数据
    this.$request.get("/department/getDepartmentOptions").then(res => {
      if (res.successFlag) {
        this.departmentOptions = res.data
      } else {
        this.$message.error("获取部门可选信息失败！")
      }
    })

  },
  methods: {
    //获取员工管理表格数据
    async getUserTableValues() {
      await this.$request.get("/user/getUserForManagerConditional", {
        params: {
          depName: "",
          userRole: this.userRoleSelectValue,
          currentPage: this.pageNum,
          pageSize: this.pageSize
        }
      }).then(res => {
        if (res.successFlag) {
          this.tableData = res.data.pageData
          this.total = res.data.totalData
        } else {
          this.$message.error(res.errorMsg)
        }
      })
    },

    //分页控件换页功能
    change(pageNum) {
      this.pageNum = pageNum;
      this.getUserTableValues();
    },

    //树形节点选中后操作
    handleNodeClick(data) {
      console.log(data);
    },

    async changeTab(queryCriteria) {
      //选择了任务状态作为条件，把分页参数重置
      this.pageNum = 1
      this.tabPosition = queryCriteria
      if (queryCriteria === "normal") {
        this.userRoleSelectValue = 3
      } else if (queryCriteria === "leader") {
        this.userRoleSelectValue = 2
      } else if (queryCriteria === "manager") {
        this.userRoleSelectValue = 1
      } else if (queryCriteria === "all") {
        this.userRoleSelectValue = 4
      }
      //点击之后便去查询
      await this.getUserTableValues()
    },
    //删除用户
    delUserAllData(userId) {
      this.$request.delete("/user/delUserAllData" + "?userId=" + userId).then(res => {
        if (res.successFlag) {
          this.$message.success("删除成功！")
          this.getUserTableValues()
        } else {
          this.$message.error(res.errorMsg)
        }
      })
    },

    //编辑用户信息
    editUserInfo() {
      this.$request.post("/user/editUserAllInfo", this.editUserEntity).then(res => {
        if (res.successFlag) {
          this.$message.success('修改信息完成！')
          this.editUserDialogVisible = false
          this.getUserTableValues()
        } else {
          this.$message.error('修改信息失败！')
          this.editUserDialogVisible = false
        }
      })

    },

    //编辑用户弹窗显示
    editUserDialogShow(userId) {

      this.$request.get("/user//getUserAllInfo", {
        params: {
          userId: userId
        }
      }).then(res => {
        if (res.successFlag) {
          this.editUserDialogVisible = true
          this.editUserEntity = res.data

        } else {
          this.editUserDialogVisible = false

        }
      })
    },

    //权限分配弹窗显示
    roleAllocationDialogShow(userId){
      this.roleVisible=true
      this.updateUserRoleId=userId
      //获取当前用户权限
      this.$request.get("/user/getUserRole", {
        params: {
          updateUserId: userId,
        }
      }).then(res => {
        if (res.successFlag) {
          //将权限选中框回填后端数据
          let foundObject = this.roleOptionValue.find(item => item.value === res.data);
          this.roleValue=foundObject.label
        } else {
          this.$message.error("获取用户权限失败！")
          this.roleVisible=false
        }
      })
    },

    //权限分配弹窗关闭
    unshowRoleVisible(){
      //将权限选中和弹窗显示重置为默认值
      this.roleValue=""
      this.roleVisible=false
      this.updateUserRoleId=""
    },

    //权限分配
    updateUserRole(){
      const uid = this.loginUser.uid;
      this.$request.put("/user/updateUserRole"+"?updateUserId="+this.updateUserRoleId+"&updateRoleNum="+this.roleValue+"&loginUserId="+uid)
          .then(res=>{
            if (res.successFlag) {
              this.$message.success("权限分配成功成功！")
              this.roleVisible=false
              //刷新页面
              window.location.reload();

            } else {
              this.$message.error(res.errorMsg)
              this.roleVisible=false
            }
      })
    },

    //新增员工弹窗显示
    addUserDialogShow(){
      this.addUserDialogVisible=true
    },

    //新增员工
    addUser(){
      let user={
        name:'',
        roleName:'普通员工',
        depName:'',
        infoName:'',
        email:'',
        phone:'',
        gender:'',
        introduction:''
      }
      this.$request.post("/user/addUser",this.addUserEntity).then(res=>{
        if (res.successFlag) {
          this.$message.success("添加成功！")
          this.addUserDialogVisible=false
          this.addUserEntity=user
          this.getUserTableValues()
        } else {
          this.$message.success("添加失败！")
          this.addUserDialogVisible=false
          this.addUserEntity=user
        }
      })
    },

    //根据UserId和员工名称条件查询
    selectUser(){
      this.$request.get("/user/selectUserConditional",{
        params:{
          selectValue:this.searchValue
        }
      }).then(res=>{
        if (res.successFlag) {
          this.tableData = res.data
        } else {
          this.$message.error(res.errorMsg)
        }
      })
    }
  }
}
</script>

<style scoped>
.deepBackground {
  display: flex;
  align-items: center;
  justify-content: left;
  /*background-color: white;*/
  border-radius: 12px;
  /* box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);*/
  height: 100vh
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>